#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Autor: Josep Torrens Amer
# E-mail: toram74@gmail.com
#
# GNU GPL License, (C) 2007.
#
# Module: dbmodul
#
# Description: Modul base de dades
#
# Version: 0.0.1
#
# Created: 27-08-2007
#
# Modified:
#
import cSingleton

try:
	import psycopg2 as dbsrc
	import psycopg2.extras
except:
	print "Error. Driver Python-postgresql no trobat"
	raise Exception.GeneralError()

class db (cSingleton.Singleton):
	"""
		Classe de gestio de base de dades
	"""

	def __init__ ( self, P_dbnom, P_usuari, P_clau="", P_host="localhost" ) :
		"""
			Constructor
		"""
		self._dbnom = P_dbnom
		self._usuari = P_usuari
		self._clau = P_clau
		self._host = P_host
		self._port = "5432"
		
	def connecta ( self ) :
		"""
			Connecta a la BD
		"""
		dsn = "host=%s dbname=%s user=%s password=%s port=%s " % (self._host, self._dbnom, self._usuari, self._clau, self._port )

		try:
			self._db = dbsrc.connect ( dsn )
			return self
		except:
			return None

			
	
	def desconnecta ( self ) :
		"""
			Desconnecta de la BD
		"""
		try:
			self._db.disconnect ()
		except:
			pass
		
	
	def _getParams ( self, Params ) :
		"""
			Params
		"""
		pass
		
		
	def getClient ( self, P_Client_ID ) :
		"""
			Obte un client donat el seu ID
		"""
		sql = "SELECT * from CLIENT WHERE CLI_ID ='%s'" % P_Client_ID
		if ( DEBUG ) :
			print "SQL: %s" % sql
			
		try:
			cur = self._db.Cursor ( cursor_factory = psycopg2.extras.DictCursor )
			
			res = cur.execute ( sql )[0]
								
			cli = client.Client ( res.id, res.nom, res.direccio1, res.direccio2 )
			
			return cli
		except:
			raise Exception.ValueError ()
			
	
	def getArreglo ( self, P_Arreglo_ID ) :
		"""
			Obte un arreglo donat el seu ID
		"""
		sql = "SELECT * from ARREGLO WHERE ARR_ID ='%s'" % P_Arreglo_ID
		if ( DEBUG ) :
			print "SQL: %s" % sql
			
		try:
			cur = self._db.Cursor ( cursor_factory = psycopg2.extras.DictCursor )
			
			res = cur.execute ( sql )[0]
								
			arr = arreglo.Arreglo ( res.id, res.nom, res.direccio1, res.direccio2 )
			
			return arr
		except:
			raise Exception.ValueError ()
			

	def Cursor (self, sql) :
		cur = self._db.Cursor (cursor_factory = psycopg2.extras.DictCursor)
		return cur.execute (sql) 
		
	
	def Execute (self, sql) :
		"""
			Executa una sentencia SQL
		"""
		
		return self._db.execute(sql)
		
